<?php 

  require_once 'init.php'; 

  /* if user logout */
  if(@$_REQUEST['action'] == 'logout'){  
    /* get facebook logout link */
    $logoutUrl = $_SESSION['user']['flogoutUrl'];
    /* destroy session */
    session_destroy();
    /* redirect to facebook logout link */
    header("Location: $logoutUrl");
  } elseif(@$_REQUEST['action'] == 'gettoken'){
    if(isset($_SESSION['user'])){

      $result = getToken(); 
      $_SESSION['user']['token'] = $result->token;          
      $smarty->assign('result', json_encode($result) );

    } else {
      die('gettoken: ko the lay dc session user <br />' . "\n");
    }
  }  

  // check if user session is exists
  if(isset($_SESSION['user'])){   
    $user_profile = $facebook->api('/me');
    if($user_profile['id'] != $_SESSION['user']['fid']) {
      $smarty->display('error.tpl');  
    }
    $smarty->display('index.tpl');  
  } else {

    // Get User ID
    $user = $facebook->getUser();

    if ($user) {
      try {
        // Proceed knowing you have a logged in user who's authenticated.
        $user_profile = $facebook->api('/me');
      } catch (FacebookApiException $e) {
        error_log($e);
        $user = null;
      }
    }       

    // Login or logout url will be needed depending on current user state.
    if ($user) {  
      // $params = array( 'next' => 'http://dsproject.com/testserver/loggedout' );
      $params = array();
      $logoutUrl = $facebook->getLogoutUrl( $params );  

    } else {
      $params = array('scope' => 'email, publish_actions, publish_stream, read_stream, offline_access');
      $loginUrl = $facebook->getLoginUrl($params);
      header("Location: $loginUrl");                                             
    }

    if( isset($user_profile['id']) && isset($user_profile['email'])){   
      $_SESSION['user'] = array('fid' => $user_profile['id'], 'femail' => $user_profile['email'], 'fname' => $user_profile['name'], 'fupdated_time' => $user_profile['updated_time'], 'token' => null, 'flogoutUrl' => $logoutUrl);                    
      $smarty->display('index.tpl');  
    } else {                                     
      $smarty->display('error.tpl');
    }                   
  } 

?>